package com.gxuwz.medical.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.gxuwz.medical.dao.UserDao;
import com.gxuwz.medical.domain.user.User;
import com.gxuwz.medical.tools.PasswordUtil;
import com.gxuwz.medical.tools.StringUtil;

/**
 * 
 * @ClassName: LoginServlet
 * @Description: 登录验证控制模块
 * @author 陈震洺
 * @date 2019年3月14日 下午3:43:36
 *
 */
public class LoginServlet extends BaseServlet {

	UserDao userUtil = new UserDao(); // 用户数据操作类
	String aesKey = "thisiskey";

	private static final Logger logger = LogManager.getLogger(LoginServlet.class);

//	private static String path = null;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		login(request, response);

	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String path = "login.jsp";
		String userid = request.getParameter("userid"); // 获取提交的userName
		String pwd = request.getParameter("pwd"); // 获取提交的password
		request.setAttribute("userid", userid); // 在请求中设置userName属性
		request.setAttribute("pwd", pwd); // 在请求中设置password属性
		// 判断为空
		if (StringUtil.isEmpty(userid) || StringUtil.isEmpty(pwd)) {
			request.setAttribute("error", "账号或密码为空!"); // 在请求中设置error属性,并赋值
			path = "login.jsp";
			return;
		}

		User user = new User(userid, pwd);
		try {
			byte[] encrypt = PasswordUtil.AESEncrypt(pwd, aesKey);// 加密
			System.out.println("AES加密后-byte[]:" + encrypt);
			String strHex = PasswordUtil.parseByte2HexStr(encrypt);
			System.out.println("转换后的十六进制:" + strHex);
			user.setPwd(strHex);

			User currentUser = userUtil.login(user); // 登录检查
			if (currentUser == null) {
				request.setAttribute("error", "用户名或密码错误！");
				// 服务器跳转
				path = "login.jsp";
			} else {
				HttpSession session = request.getSession();
				// 客户端跳转
				path = "index.jsp";
				// response.sendRedirect("index.jsp");
				session.setAttribute("currentUser", currentUser); // 在session中设置用户
				System.out.println(session.getAttribute("currentUser"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 跳转页面
		process(request, response, path);
	}

}
